package com.test.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.util.StringUtil;
import org.springframework.context.MessageSource;

import com.alibaba.fastjson.JSON;

import ch.qos.logback.classic.gaffer.PropertyUtil;

public abstract class BaseController {

//	protected final Logger logger = Logger.getLogger(this.getClass());
	
	public static final String TYPE_PDF = "application/pdf;charset=utf-8";
	public static final String TYPE_EXCEL = "application/x-xls;charset=utf-8";

	@Resource(name = "messageSource")
	private MessageSource messageSource;

	/**
	 * 获取当前登录用户信息
	 * 
	 * @param request
	 * @return
	 */
//	public UserInfo getUserInfo(HttpServletRequest request) {
//		HttpSession session = request.getSession();
//
//		UserInfo user = (UserInfo) session.getAttribute(Constants.USER_INFO);
//		return user;
//	}

	/**
	 * 获取存储共享文件夹
	 * 
	 * @return
	 */
//	public String getShareDir() {
//		String shareDir = "";
//		try {
//			Properties po = PropertyUtil.getInstance().getPropertiesByFileName(
//					Constants.CONFIG_FILE);
//			shareDir = StringUtil.trim(po.getProperty(Constants.SHAIR_DIR));
//		} catch (IOException e) {
//			throw new IllegalArgumentException(" NOT found!", e);
//		}
//
//		return shareDir;
//	}

	/**
	 * 获取配置值
	 * 
	 * @param key
	 * @return
	 */
//	public String getConfig(String key) {
//		String shareDir = "";
//		try {
//			Properties po = PropertyUtil.getInstance().getPropertiesByFileName(
//					Constants.CONFIG_FILE);
//			shareDir = StringUtil.trim(po.getProperty(key));
//		} catch (IOException e) {
//			throw new IllegalArgumentException(" NOT found!", e);
//		}
//
//		return shareDir;
//	}

	/**
	 * 为response提供Json格式的返回数据
	 * 
	 * @param obj
	 *            任何对象
	 * @return void
	 */
	public void writeResponse(Object obj, HttpServletResponse response) {
		try {
			response.setContentType("text/json;charset=utf-8");

			String str = JSON.toJSONString(obj);

			PrintWriter writer;
			writer = response.getWriter();
			writer.write(str);
			System.out.println("str==" +str);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 为response提供String数据的返回，字符集为utf-8
	 * 
	 * @param str
	 *            字符串
	 * @return void
	 */
	public void writeResponseStr(String str, HttpServletResponse response) {

		writeResponseStr(str, response, "utf-8");
	}

	/**
	 * 为response提供String数据的返回
	 * 
	 * @param str
	 *            字符串
	 * @param encoding
	 *            字符编码
	 */
	public void writeResponseStr(String str, HttpServletResponse response,
			String encoding) {
		try {
			response.setContentType("text/html;charset=" + encoding);

			PrintWriter writer;
			writer = response.getWriter();
			writer.write(str);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取当前登录用户的IP地址
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
//	public String getIpAddr(final HttpServletRequest request) throws Exception {
//		String ip = request.getHeader("X-Real-IP");
//		if (!StringUtil.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
//			return ip;
//		}
//		ip = request.getHeader("X-Forwarded-For");
//		if (!StringUtil.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
//			// 多次反向代理后会有多个IP值，第一个为真实IP。
//			int index = ip.indexOf(',');
//			if (index != -1) {
//				return ip.substring(0, index);
//			} else {
//				return ip;
//			}
//		} else {
//			return request.getRemoteAddr();
//		}
//	}

	/**
	 * 获取请求参数中所有的信息
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> getAllRequestParam(
			final HttpServletRequest request) {
		Map<String, String> res = new HashMap<String, String>();
		Enumeration<?> temp = request.getParameterNames();
		if (null != temp) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				res.put(en, value);

				// 在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
				if (null == res.get(en) || "".equals(res.get(en))) {
					res.remove(en);
				}
			}
		}
		return res;
	}

	/**
	 * excel文件下载，支持excel文件类型的下载。
	 */
	public void downloadFile(HttpServletRequest request,
			HttpServletResponse response, String fileName, String filePath,String type) {
		// 下载的文件
		File file = new File(filePath + fileName);
		InputStream inStream = null;
		try {
			/* 如果文件存在 */
			if (file.exists()) {
				response.reset();
				response.setContentType(type);
				String fileDownName = new String(fileName.getBytes("gbk"),
						"iso8859-1");
				response.addHeader("Content-Disposition",
						"attachment; filename=\"" + fileDownName + "\"");
				int fileLength = (int) file.length();
				response.setContentLength(fileLength);
				/* 如果文件长度大于0 */
				if (fileLength != 0) {
					/* 创建输入流 */
					inStream = new FileInputStream(file);
					byte[] buf = new byte[4096];
					/* 创建输出流 */
					ServletOutputStream servletOS = response.getOutputStream();
					int readLength;
					while (((readLength = inStream.read(buf)) != -1)) {
						servletOS.write(buf, 0, readLength);
					}
					servletOS.flush();
					servletOS.close();
				}

			}

		} catch (Exception ex) {
//			logger.error("文件下载出错:" + ex);
		} finally {
			safeClose(inStream);
		}
	}
	

	private void safeClose(InputStream inStream) {
		if(inStream != null){
			try {
				inStream.close();
			} catch (IOException e) {
//				logger.error("InputStream close exception:" + e);
			}
		}
	}

	/**
	 * 依据语言不同，获取配置文件中key对应的字符串
	 * 
	 * @since
	 * @param key
	 * @param request
	 * @return
	 */
	public String getLocale(String key, final HttpServletRequest request) {
		String value = messageSource.getMessage(key, new Object[0],
				request.getLocale());
		return value;
	}


}
